package com.dynamic.mybatis.demo;

import com.alibaba.fastjson.JSON;
import com.dynamic.mybatis.config.DynamicMybatisSQLHandle;
import com.dynamic.mybatis.core.builder.DynamicMapperAdapterBuilder;
import com.dynamic.mybatis.core.enums.ReturnType;
import com.dynamic.mybatis.core.metadata.DynamicPage;
import com.dynamic.mybatis.core.metadata.DynamicScriptMappedStatement;
import com.dynamic.mybatis.core.metadata.DynamicXmlMappedStatement;
import com.dynamic.mybatis.core.session.DynamicSqlSessionTemplate;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.session.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author xs
 * @Date 2021/3/25 16:52
 */
@Component
public class DynamicMybatisDemoRunner  implements ApplicationRunner {

    @Autowired
    private DynamicMybatisSQLHandle dynamicMybatisSQLHandle;

    @Autowired
    private DynamicSqlSessionTemplate sqlSessionTemplate;

    public void test() {
        String str = "    <resultMap id=\"queryResourceAssemblyTemplateResultMap\" type=\"java.util.Map\">\n" + "        <id column=\"id\" property=\"id\"/>\n" + "        <result column=\"code\" property=\"code\"/>\n" + "        <result column=\"name\" property=\"title\"/>\n" + "        <result column=\"userId\" property=\"userId\"/>\n" + "        <collection property=\"assembles\" select=\"queryResourceAssembly\" javaType=\"java.util.List\"  ofType=\"java.util.Map\" column=\"{resourceId=id}\"/>\n" + "        <collection property=\"resourceFiles\" select=\"queryResourceAssemblyFile\" javaType=\"java.util.List\"  ofType=\"java.util.Map\" column=\"{menuCode=code}\" />\n" + "        <collection property=\"buttons\" select=\"queryResourceAssemblyButton\" javaType=\"java.util.List\"  ofType=\"java.util.Map\" column=\"{parentId=id,userId=userId}\" />\n" + "    </resultMap>\n" + "\n" + "    <resultMap id=\"queryResourceAssemblyResultMap\" type=\"java.util.Map\">\n" + "        <id column=\"id\" property=\"id\"/>\n" + "        <result column=\"resource_id\" property=\"resourceId\"/>\n" + "        <result column=\"code\" property=\"code\"/>\n" + "        <result column=\"title\" property=\"assemblyTitle\"/>\n" + "        <result column=\"sort\" property=\"sort\"/>\n" + "        <result column=\"type\" property=\"assemblyType\"/>\n" + "        <result column=\"expand\" property=\"expand\"/>\n" + "        <result column=\"alias\" property=\"alias\"/>\n" + "        <association property=\"assembly\" select=\"queryDynamicResourceAssembly\"  javaType=\"java.util.Map\"   column=\"{assemblyType=type,assemblyCode=code}\"></association>\n" + "        <collection property=\"resourceFiles\" select=\"queryResourceAssemblyFile\" javaType=\"java.util.List\"  ofType=\"java.util.Map\" column=\"{assemblyType=type,assemblyCode=code}\" />\n" + "    </resultMap>\n" + "\n" + "    <resultMap id=\"queryResourceAssemblyButtonResultMap\" type=\"java.util.Map\">\n" + "        <result column=\"id\" property=\"id\"/>\n" + "        <result column=\"code\" property=\"code\"/>\n" + "        <result column=\"name\" property=\"name\"/>\n" + "        <result column=\"type\" property=\"type\"/>\n" + "        <result column=\"url\" property=\"url\"/>\n" + "        <result column=\"css\" property=\"css\"/>\n" + "        <result column=\"icon\" property=\"icon\"/>\n" + "        <result column=\"is_display\" property=\"isDisplay\"/>\n" + "        <result column=\"sort\" property=\"sort\"/>\n" + "        <result column=\"static_type\" property=\"staticType\"/>\n" + "        <result column=\"method\" property=\"method\"/>\n" + "        <result column=\"status\" property=\"status\"/>\n" + "        <result column=\"parameter\" property=\"parameter\"/>\n" + "        <result column=\"expand\" property=\"expand\"/>\n" + "    </resultMap>\n" + "\n" + "\n" + "    <resultMap id=\"queryDynamicResourceAssemblyResultMap\" type=\"java.util.Map\">\n" + "        <discriminator javaType=\"int\" column=\"assemblyType\">\n" + "            <case value=\"1\" resultType=\"java.util.Map\">\n" + "                <result column=\"gridId\" property=\"id\"/>\n" + "                <result column=\"gridCode\" property=\"code\"/>\n" + "                <result column=\"sql_code\" property=\"statementCode\"/>\n" + "                <result column=\"gridName\" property=\"title\"/>\n" + "                <result column=\"gridFormCode\" property=\"formCode\"/>\n" + "                <result column=\"gridSelectType\" property=\"selectType\"/>\n" + "                <result column=\"gridPagination\" property=\"pagination\"/>\n" + "                <result column=\"gridInit\" property=\"initialize\"/>\n" + "                <result column=\"gridExpand\" property=\"expand\"/>\n" + "                <collection property=\"fields\"  javaType=\"java.util.List\"  ofType=\"java.util.Map\" >\n" + "                    <result column=\"id\" property=\"id\"/>\n" + "                    <result column=\"field\" property=\"field\"/>\n" + "                    <result column=\"name\" property=\"title\"/>\n" + "                    <result column=\"type\" property=\"type\"/>\n" + "                    <result column=\"editor\" property=\"editor\"/>\n" + "                    <result column=\"dict_code\" property=\"dictCode\"/>\n" + "                    <result column=\"sort\" property=\"sort\"/>\n" + "                    <result column=\"align\" property=\"align\"/>\n" + "                    <result column=\"is_display\" property=\"visible\"/>\n" + "                    <result column=\"formatter\" property=\"formatter\"/>\n" + "                </collection>\n" + "            </case>\n" + "            <case value=\"2\" resultType=\"java.util.Map\">\n" + "                <result column=\"formId\" property=\"id\"/>\n" + "                <result column=\"formCode\" property=\"code\"/>\n" + "                <result column=\"sql_code\" property=\"statementCode\"/>\n" + "                <result column=\"formName\" property=\"name\"/>\n" + "                <result column=\"formType\" property=\"type\"/>\n" + "                <result column=\"formCss\" property=\"css\"/>\n" + "                <result column=\"formFence\" property=\"fence\"/>\n" + "                <result column=\"formPlaceholder\" property=\"placeholder\"/>\n" + "                <result column=\"formSqlCode\" property=\"sqlCode\"/>\n" + "                <collection property=\"fields\"  javaType=\"java.util.List\"  ofType=\"java.util.Map\" >\n" + "                    <result column=\"id\" property=\"id\"/>\n" + "                    <result column=\"field\" property=\"field\"/>\n" + "                    <result column=\"name\" property=\"name\"/>\n" + "                    <result column=\"type\" property=\"type\"/>\n" + "                    <result column=\"dict_code\" property=\"dictCode\"/>\n" + "                    <result column=\"sort\" property=\"sort\"/>\n" + "                    <result column=\"align\" property=\"align\"/>\n" + "                    <result column=\"is_display\" property=\"isDisplay\"/>\n" + "                    <result column=\"formatter\" property=\"formatter\"/>\n" + "                    <result column=\"expand\" property=\"expand\"/>\n" + "                    <result column=\"formatter\" property=\"formatter\"/>\n" + "                    <result column=\"validator\" property=\"validator\"/>\n" + "                </collection>\n" + "            </case>\n" + "        </discriminator>\n" + "    </resultMap>\n" + "\n" + "\n" + "    <select id=\"queryResourceAssemblyTemplate\" resultMap=\"queryResourceAssemblyTemplateResultMap\">\n" + "        select r.id , r.code,#{userId} as userId,r.name\n" + "        from resource r\n" + "        where r.is_deleted = 0\n" + "        <if test=\"resourceId != null and resourceId != ''\">\n" + "            and r.id = #{resourceId}\n" + "        </if>\n" + "    </select>\n" + "\n" + "    <select id=\"queryResourceAssembly\" resultMap=\"queryResourceAssemblyResultMap\">\n" + "        select ra.id  , ra.code , ra.title , ra.sort ,ra.type  ,ra.expand ,ra.alias\n" + "        from   resource_assembly ra\n" + "        where ra.is_deleted = 0\n" + "        <if test=\"resourceId != null and resourceId != ''\">\n" + "            and ra.resource_id = #{resourceId}\n" + "        </if>\n" + "        order by ra.sort\n" + "    </select>\n" + "\n" + "    <select id=\"queryResourceAssemblyFile\"  resultType=\"java.util.Map\">\n" + "        select\n" + "        rf.id, rf.type,rf.sort, rf.src\n" + "        from resource_file rf\n" + "        where rf.is_deleted = 0\n" + "        <trim prefix=\"and (\" suffixOverrides=\"or\"   suffix=\")\">\n" + "            <if test=\"menuCode!= null and menuCode!= ''\">\n" + "                (rf.code = #{menuCode} and belong_type= 1)\n" + "            </if>\n" + "            <if test=\"gridCode!= null and gridCode!= ''\">\n" + "                (rf.code = #{gridCode} and belong_type= 2)\n" + "            </if>\n" + "            <if test=\"formCode!= null and formCode!= ''\">\n" + "                (rf.code = #{formCode} and belong_type= 3)\n" + "            </if>\n" + "            <if test=\"assemblyType == 1 and assemblyCode != null and assemblyCode !=''\">\n" + "                (rf.code = #{assemblyCode} and belong_type= 2)\n" + "            </if>\n" + "            <if test=\"assemblyType == 2 and assemblyCode != null and assemblyCode !=''\">\n" + "                (rf.code = #{assemblyCode} and belong_type= 3)\n" + "            </if>\n" + "        </trim>\n" + "        order by rf.sort\n" + "    </select>\n" + "\n" + "    <select id=\"queryResourceAssemblyButton\"  parameterType=\"java.util.HashMap\" resultMap=\"queryResourceAssemblyButtonResultMap\">\n" + "        select\n" + "        r.id,r.code,r.name,r.url,r.css,r.icon,r.is_display,r.sort,\n" + "        rb.type,rb.static_type,rb.method,rb.status,rb.parameter,rb.expand\n" + "        from resource r\n" + "        <if test=\"userId!=null\">\n" + "            join role_resource rr on rr.resource_id  =  r.id\n" + "            join role on role.id = rr.role_id\n" + "            join user_role ur on ur.role_id = role.id and ur.user_id = #{userId}\n" + "        </if>\n" + "        left join resource_button rb  on r.id = rb.resource_id and rb.is_deleted = 0\n" + "        where r.is_deleted = 0\n" + "        <if test=\"menuCode != null and menuCode != ''\">\n" + "            and r.parent_id in ( select id from resource pr where pr.code = #{menuCode})\n" + "        </if>\n" + "        <if test=\"parentId != null and parentId != ''\">\n" + "            and r.parent_id = #{parentId}\n" + "        </if>\n" + "        order by r.sort\n" + "    </select>\n" + "\n" + "\n" + "\n" + "    <select id=\"queryDynamicResourceAssembly\" resultMap=\"queryDynamicResourceAssemblyResultMap\">\n" + "        <if test=\"assemblyType == 1 \">\n" + "            select\n" + "            g.id gridId,g.code gridCode,g.sql_code, g.name gridName,g.form_code gridFormCode,g.select_type as gridSelectType,g.is_init as gridInit,\n" + "            g.is_page as gridPagination,g.expand as gridExpand, #{assemblyType} assemblyType,#{assemblyCode} assemblyCode,\n" + "            gf.id,gf.field, gf.name,gf.type,gf.dict_code,gf.editor,gf.sort,gf.align,gf.is_display,gf.formatter\n" + "            from grid g\n" + "            left join grid_field gf on g.code = gf.grid_code and gf.is_deleted = 0\n" + "            <if test=\"assemblyCode != null and assemblyCode != ''\">\n" + "                where g.code = #{assemblyCode}\n" + "            </if>\n" + "            order by gf.sort\n" + "        </if>\n" + "        <if test=\"assemblyType == 2 \">\n" + "            select\n" + "            f.id as formId,f.code as formCode,f.name formName,f.type formType,f.css formCss,f.fence formFence,\n" + "            f.placeholder formPlaceholder,f.sql_code ,#{assemblyType} assemblyType,#{assemblyCode} assemblyCode,\n" + "            ff.id,ff.field, ff.name,ff.type,ff.dict_code,ff.sort,ff.fence,ff.is_display,ff.expand,ff.formatter,ff.validator\n" + "            from form f\n" + "            left join form_field ff on ff.code = f.code and ff.is_deleted = 0\n" + "            <if test=\"assemblyCode!= null and assemblyCode!= ''\">\n" + "                where f.code = #{assemblyCode}\n" + "            </if>\n" + "            order by ff.sort\n" + "        </if>\n" + "    </select>";
        DynamicXmlMappedStatement dxs = new DynamicXmlMappedStatement();
        dxs.setMappedStatement(str);
        dxs.setId("queryResourceAssemblyTemplate");
        Map<String,Object> parameter = new HashMap<>();
        parameter.put("resourceId",107);
        parameter.put("gridCode","gridGridCfg");

        new DynamicMapperAdapterBuilder(sqlSessionTemplate.getDynamicSqlSession().getSqlSession().getConfiguration())
                .parser(dxs);

        Object result =   sqlSessionTemplate.executeTest(dxs,parameter);

        System.out.println(JSON.toJSONString(result));
    }



    @Override
    public void run(ApplicationArguments args) {

        test();

   /*     new Thread(() -> {
             queryDataBaseDateTime();
             queryTables();
             dynamicSqlInit();//无数据库动态SQL表，注释该行代码
        }).start();*/
    }

    //分页查询表
    private void queryTables(){
        Configuration configuration = sqlSessionTemplate.getDynamicSqlSession().getSqlSession().getConfiguration();
        String id = "queryTables";
        String sql = "select table_name from information_schema.tables where table_schema='mysql'";
        DynamicScriptMappedStatement dms =  new DynamicScriptMappedStatement.Builder()
                .setId(id)
                .setResultType("java.lang.String")
                .setResultMap(null)
                .setSqlCommandType(SqlCommandType.SELECT)
                .setMappedStatement(sql)
                .setReturnType(ReturnType.PAGE).builder();
        //初始化动态SQL
        new DynamicMapperAdapterBuilder(configuration).parser(dms);
        //执行SQL
        System.out.println();
        System.out.println("queryTables ==================== start");
        int pageNumber = 1;
        while (true){
            Map<String,Object> parameter = new HashMap<>();
            parameter.put(DynamicPage.PAGE_NUMBER,pageNumber);
            DynamicPage pagination =  sqlSessionTemplate.execute(id,parameter);
            System.out.println(JSON.toJSONString(pagination)) ;
            if(pagination.getRecords() == null || pagination.getRecords().size() < pagination.getPageSize()){
                break;
            }
            pageNumber++;
        }
        System.out.println("queryTables ==================== end");
    }

    //查询数据库信息
    private void  queryDataBaseDateTime(){
        Configuration configuration = sqlSessionTemplate.getDynamicSqlSession().getSqlSession().getConfiguration();
        String id = "queryDataBaseDateTime";
        String sql = "select DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%S') currentDateTime , database() databaseName";
        DynamicScriptMappedStatement dms =  new DynamicScriptMappedStatement.Builder()
                .setId(id)
                .setSqlCommandType(SqlCommandType.SELECT)
                .setMappedStatement(sql)
                .setResultType("java.lang.String")
                .setResultMap(null)
                .setReturnType(ReturnType.MAP).builder();

        //初始化动态SQL
       new  DynamicMapperAdapterBuilder(configuration).parser(dms);
        //执行SQL
        System.out.println();
        System.out.println("queryDataBase ==================== start");
        System.out.println(JSON.toJSONString(sqlSessionTemplate.execute(id))) ;
        System.out.println("queryDataBase ==================== end");
    }

    //初始化动态SQL
    private void dynamicSqlInit(){
        dynamicMybatisSQLHandle.dynamicMappedStatementInit();
    }

}